<template>
  <div class="buy-container">
    <Header :getGoods="getGoods"  />
    <div class="buy-main">
      <div class="buy-main-left">
        <h3>确认订单信息</h3>
        <hr/>
        <div v-if="goodsItems.length > 0">
          <div v-for="item in goodsItems" :key="item.id" class="goodsByCar">
            <img :src="item.imgPath" alt="Item Image" class="item-image" />
            <div class="item-details">
              <h3>{{ item.name }}</h3>
              <p>{{ item.state }}</p>
              <p>价格: {{ item.price }}</p>
            </div>
          </div>
        </div>
        <div v-if="soloBuysItems">
          <img :src="soloBuysItems.imgPath" alt="Item Image" class="item-image-solo" />
          <div class="item-details">
            <h3>{{ soloBuysItems.name }}</h3>
            <p>{{ soloBuysItems.state }}</p>
            <p>价格: {{ soloBuysItems.price }}</p>
          </div>
        </div>
      </div>

      <!-- 付款详情部分 -->
      <div class="buy-main-right">
        <h3>付款详情</h3>
        <p>共 {{ itemCount }} 件商品</p>
        <p>商品总价: {{ totalPrice }} 元</p>
        <button @click="goBack">返回</button>
        <button @click="submitOrder">提交订单</button>
      </div>
    </div>
    <div v-if="showDialog" class="dialog-overlay">
        <div class="dialog">
            <div class="dialog-top">
                <el-icon class="showPay-close-button" @click="showDialog = false"><Close /></el-icon>
            </div>
            <div class="dialog-min">
                <div class="dialog-min-left">
                    <img class="wechatPay" src="/public/img/wechatPay.jpg"/>
                </div>
                <div class="dialog-min-right">
                    <img class="aliPay"  src="/public/img/aliPay.jpg"/>
                </div>
            </div>
            <div class="dialog-bot">
                <button class="confirmPay" @click="confirmPlay">确认支付</button>
            </div>
        </div>
      </div>
  </div>
</template>


<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue';
import Header from './Header.vue';
import '../css/goodsDetail.css';
import axios from 'axios';
import "../css/buy.css"
import { useRoute, useRouter } from 'vue-router';

interface GoodsItem {
  id: number;
  imgPath: string;
  name: string;
  state: string;
  price: number;
}

interface SoloBuyItem {
  id: number;
  imgPath: string;
  name: string;
  state: string;
  price: number;
}

const route = useRoute();
const router = useRouter();
const selectedIds = ref<number[]>([]);
const goodsId = ref<number | null>(null);
const goodsItems = ref<GoodsItem[]>([]);
const soloBuysItems = ref<SoloBuyItem | null>(null);
const showDialog = ref(false);

const token = localStorage.getItem('token');
const userId = localStorage.getItem('userId');

const getIdsLink = "http://localhost:8080/goods/getIds";
const getIdLink = "http://localhost:8080/goods/getId";
const obligationLink = "http://localhost:8080/order/obligation";
const pendingReceiptLink = "http://localhost:8080/order/pendingReceipt";

// 计算总商品数和总价格
const itemCount = computed(() => {
  return goodsItems.value.length > 0 ? goodsItems.value.length : (soloBuysItems.value ? 1 : 0);
});

const totalPrice = computed(() => {
  if (goodsItems.value.length > 0) {
    return goodsItems.value.reduce((total, item) => total + item.price, 0);
  } else if (soloBuysItems.value) {
    return soloBuysItems.value.price;
  }
  return 0;
});

const goBack = () => {
  router.go(-1);
};


// 判断用户是直接买还是通过购物车买
const determineTheSource = () => {
  const ids = route.query.ids as string;
  if (ids) {
    selectedIds.value = ids.split(',').map(id => parseInt(id, 10));
    buyFormCar(selectedIds.value);
  } else if (route.query.id) {
    goodsId.value = parseInt(route.query.id as string, 10);
    soloBuy(goodsId.value);
  }
};

const soloBuy = async (goodsId: number) => {
  if (!token) {
    router.push({ name: 'Login' });
  } else {
    try {
      const response = await axios.post(getIdLink, goodsId, {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
      });
      soloBuysItems.value = response.data.data;
    } catch (error) {
      console.log(error);
    }
  }
};

const buyFormCar = async (selectedIds: number[]) => {
  if (!token) {
    router.push({ name: 'Login' });
  } else {
    try {
      const response = await axios.post(getIdsLink, selectedIds, {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
      });
      goodsItems.value = response.data.data;
    } catch (error) {
      console.log(error);
    }
  }
};

const submitOrder = async () => {
  showDialog.value = true;

  let itemIds: number[] = [];
  if (goodsItems.value.length > 0) {
    itemIds = goodsItems.value.map(item => item.id);
  } else if (soloBuysItems.value !== null) {
    itemIds = [soloBuysItems.value.id];
  }

  const order = {
    userId: userId,
    goodsId: itemIds
  };

  if (!token) {
    router.push({ name: 'Login' });
  } else {
    try {
      const response = await axios.post(obligationLink, order, {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
      });
      // 处理提交成功的逻辑
    } catch (error) {
      console.error('订单提交失败:', error);
      alert('订单提交失败，请稍后再试。');
    }
  }
};

const confirmPlay  =  async()=>{
  showDialog.value = false

  let itemIds: number[] = [];
  if (goodsItems.value.length > 0) {
    itemIds = goodsItems.value.map(item => item.id);
  } else if (soloBuysItems.value !== null) {
    itemIds = [soloBuysItems.value.id];
  }

  const order = {
    userId: userId,
    goodsId: itemIds
  };

  if (!token) {
    router.push({ name: 'Login' });
  } else {
    try {
      const response = await axios.post(pendingReceiptLink, order, {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
      });
      // 处理提交成功的逻辑
      const result = response.data;
      const state = result.state;
      if(state){
        alert('付款成功');
        if (token) {
          router.push({ name: 'UserInfo' });
        }
      }
    } catch (error) {
      console.error('订单提交失败:', error);
      alert('订单提交失败，请稍后再试。');
    }
  }
}

const getGoods = (filterObject: { name: string; platform: string; sortType: string; categoriesId: number }) => {
  
};
onMounted(() => {
  determineTheSource();
});
</script>
